package Spring5.第二章.demo2_1;


import Spring5.common.Student;

import java.sql.*;

public class DemoJdbc {
    public static void main(String[] args) {
        save();
    }

    public static void save() {
        String sql = "insert into t_student (name, age) values (?, ?)";
        Student stu = new Student("zhangsan", 15);
        Connection connection = null;
        Statement statement = null;
        try {
            // 1 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2 获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql:///designmodel", "root", "root");
            // 3 创建语句对象
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setObject(1, stu.getName());
            ps.setObject(2, stu.getAge());
            // 4 执行sql语句
            ps.executeUpdate();
            // 5 释放连接
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
